package com.cskaoyan.mall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cskaoyan.mall.common.constant.RedisConst;
import com.cskaoyan.mall.user.consts.UserConstants;
import com.cskaoyan.mall.user.dto.UserLoginDTO;
import com.cskaoyan.mall.user.dto.UserLoginInfoDTO;
import com.cskaoyan.mall.user.mapper.UserInfoMapper;
import com.cskaoyan.mall.user.model.UserAddress;
import com.cskaoyan.mall.user.model.UserInfo;
import com.cskaoyan.mall.user.query.UserInfoParam;
import com.cskaoyan.mall.user.service.UserService;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
 * @author Macro_Ray
 * @since 2024/6/19 下午2:33
 */
@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {

    // 调用 mapper 层
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedissonClient redissonClient;

    /**用户登录*/
    @Override
    public UserLoginDTO login(UserInfoParam userInfo, String ip, String token) {

        // 1. 根据用户的用户名和密码去匹配
        // 1.1 将前端传递的明文密码 ——> 密文密码
        String newPasswd = DigestUtils.md5DigestAsHex(userInfo.getPasswd().getBytes());

        // 1.2 构造条件查询
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        //用户名
        queryWrapper.eq(UserInfo::getLoginName, userInfo.getLoginName());
        // 密码
        queryWrapper.eq(UserInfo::getPasswd, newPasswd);

        UserInfo userLoginInfo = userInfoMapper.selectOne(queryWrapper);
        if (userLoginInfo == null) {
            // 匹配失败
            return null;
        }

        // 2.向Redis中保存用户登录成功的信息
        // 2.1 构造登录信息
        UserLoginInfoDTO userLoginInfoDTO = new UserLoginInfoDTO();
        // 设置用户id
        userLoginInfoDTO.setUserId(userLoginInfo.getId().toString());
        userLoginInfoDTO.setIp(ip);

        // 2.2 存到redis中
        RBucket<UserLoginInfoDTO> bucket
                = redissonClient.getBucket(UserConstants.USER_LOGIN_KEY_PREFIX + token);

        // 保存登录信息并设置过期时间
        bucket.set(userLoginInfoDTO, UserConstants.USERKEY_TIMEOUT, TimeUnit.SECONDS);

        return new UserLoginDTO(userLoginInfo.getNickName(), token);
    }

    /**
     * 用于给其他服务调用，根据用户Id 查询用户的收货地址列表！
     * @param userId
     */
    @Override
    public List<UserAddress> findUserAddressListByUserId(String userId) {
        // todo
        return List.of();
    }
}
